package com.hefan.user.service;

import com.cat.common.entity.Page;
import com.cat.tiger.service.JedisService;
import com.cat.tiger.util.GlobalConstants;
import com.hefan.common.pay.alipay.sdk.StringUtils;
import com.hefan.user.bean.RecommendForStar;
import com.hefan.user.bean.WebUser;
import com.hefan.user.dao.FansRelationDao;
import com.hefan.user.dao.WatchRelationDao;
import com.hefan.user.dao.WebUserDao;
import com.hefan.user.itf.WatchCacheService;
import com.hefan.user.itf.WatchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component("watchService")
public class WatchServiceImpl implements WatchService{

	Logger logger = LoggerFactory.getLogger(WatchServiceImpl.class);


	private Integer redis_out_time = 500;
	
	@Resource
	WatchRelationDao watchRelationDao;
	
	@Resource
	FansRelationDao fansRelationDao;
	
	@Resource
	private JedisService jedisService;
	
	@Resource
	WebUserDao webUserDao;

	@Resource
	WatchCacheService watchCacheService;
	
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public int fork(String userId, String mainUserId,Integer liveRemind) {
		fansRelationDao.saveObj(userId, mainUserId);
		if(watchRelationDao.saveObj(userId, mainUserId,liveRemind)==0){
			//关注关系建立后，更新被关注人的redis粉丝列表
		/*	try{
				watchCacheService.refreshFanCacheList(mainUserId);
			}catch (Exception e){
				logger.error("缓存用户userId={}粉丝userId={}关注异常", mainUserId, userId, e);
			}*/
			return 1;
		}
			return 0;
	}
	
	/**
	 * 操作执行删除 无论成功与否 异常由controller层统一处理
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public int unfork(String userId, String mainUserId) {
		fansRelationDao.delObj(userId, mainUserId);
		watchRelationDao.delObj(userId, mainUserId);
		return 0;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Page listWatchAnchorInfo(Page page,String userId) {
		String sql =" select w.user_level userLevel,w.head_img headImg ,w.person_sign personalSignature ,"
				+ " w.sex sex,w.nick_name nickName,w.user_id userId ,w.user_type userType,wr.id relationId,wr.live_remind liveRemind"
				+ " from web_user w,watch_relation wr "
				+ " where w.user_id = wr.main_user_id "
				+ " and wr.user_id = ? " ;
		Object[] params = new Object[]{userId};
		return watchRelationDao.findPageMap(page, sql, params);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Page listFansInfo(Page page,String userId) {
		String sql =" select wr.id,w.user_level userLevel,w.head_img headImg ,w.person_sign personalSignature ,"
				+ " w.sex sex,w.nick_name nickName,w.user_id userId ,w.user_type userType"
				+ " from web_user w,fans_relation wr "
				+ " where w.user_id = wr.user_id "
				+ " and wr.main_user_id = ? " ;
		Object[] params = new Object[]{userId};
		return watchRelationDao.findPageMap(page, sql, params);
	}

	/**
	 * 更新首次进入俱乐部的状态
	 *
	 * @param userId
	 * @param mainUserIds
	 * @return
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public int updateFirstEnterClubStatus(String userId, String mainUserIds) {
		String sql = "update web_user set to_club_status = 1 where user_id=? ";
		return webUserDao.update(sql, new Object[]{userId});
	}

	@Override
	@Transactional(readOnly = true)
	public long findWatchedCount(String userId) {
		return watchCacheService.watchNum(userId);
	}

	@Override
	@Transactional(readOnly = true)
	public long findFansCount(String userId) {
		long fansNumLong;
		String fansNumStr;
		try {
			fansNumStr =  jedisService.getStr(GlobalConstants.FANS_NUM_REDIS_KEY+userId);	
			if(StringUtils.isEmpty(fansNumStr)){
				fansNumLong = fansRelationDao.findFansCount(userId);
				jedisService.setexStr(GlobalConstants.FANS_NUM_REDIS_KEY+userId,String.valueOf(fansNumLong),redis_out_time);
			}else{
				fansNumLong = Long.parseLong(fansNumStr);
			}
		} catch (Exception e) {
			fansNumLong = fansRelationDao.findFansCount(userId);
		}
		return fansNumLong;
	}
	
	@Override
	public long findAllFansCount(String userId) {
		return findFansCount(userId)+getExtraFans(userId);
	}
	
	private long getExtraFans(String userId){
		long extrafansNumLong;
		String extrafansNumStr;
		try {
			extrafansNumStr =  jedisService.getStr(GlobalConstants.EXTRA_FANS_NUM_REDIS_KEY+userId);	
			if(StringUtils.isEmpty(extrafansNumStr)){
				extrafansNumLong = fansRelationDao.findFansCount(userId);
				String sql = "select * from web_user where user_id=? and is_del=0";
		        List<Object> params = new ArrayList<Object>();
		        params.add(userId);
		        WebUser webUser =  webUserDao.get(sql,params,WebUser.class);
		        if(webUser!=null){
		        	extrafansNumLong =  webUser.getExtraFans();
		        }else{
		        	extrafansNumLong =  0;
		        }
				jedisService.setexStr(GlobalConstants.EXTRA_FANS_NUM_REDIS_KEY+userId,String.valueOf(extrafansNumLong),redis_out_time);
			}else{
				extrafansNumLong = Long.parseLong(extrafansNumStr);
			}
		} catch (Exception e) {
			extrafansNumLong = fansRelationDao.findFansCount(userId);
			String sql = "select * from web_user where user_id=? and is_del=0";
	        List<Object> params = new ArrayList<Object>();
	        params.add(userId);
	        WebUser webUser =  webUserDao.get(sql,params,WebUser.class);
	        if(webUser!=null){
	        	extrafansNumLong =  webUser.getExtraFans();
	        }else{
	        	extrafansNumLong =  0;
	        }
		}
		return extrafansNumLong;
	}
	@Override
	@Transactional(readOnly = true)
	public int isWatchedCheck(String userId, String beViUserId) {
		return watchRelationDao.isWatchedCheck(userId, beViUserId);
	}

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updateWatchRelationForLiveRemind(Long relationId, int LiveRemind) {
        // TODO Auto-generated method stub
        return watchRelationDao.updateWatchRelationForLiveRemind(relationId, LiveRemind);
    }

    @Override
    public List<RecommendForStar> recommendMesStarClubFor(String userIds) {

        return watchRelationDao.recommendMesStarClubFor(userIds);
    }

    @Override
    public Map getrelationIds(String userId) {

        return watchRelationDao.getrelationIds(userId);
    }
	/**
	 * 删除关注粉丝相关redisKey
	 * @param userId
	 */
	@Override
	public void flushWatchRedis(String userId){
		try {
			jedisService.del(GlobalConstants.FANS_NUM_REDIS_KEY+userId);
			jedisService.del(GlobalConstants.EXTRA_FANS_NUM_REDIS_KEY+userId);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
